from osgeo import gdal
import numpy as np
import transfrom2 as tf


def getValByLonLat(tifUrl, lon, lat):
    '''
    tifUrl,tif文件路径
    lon,lat经纬度
    '''
    # tif存储的数据集
    dataset = gdal.Open(tifUrl, gdal.GA_ReadOnly)
    # 经纬度转像素坐标
    [px, py] = tf.main(dataset, lon, lat)
    # 栅格矩阵的列数
    im_width = dataset.RasterXSize
    # 栅格矩阵的行数
    im_height = dataset.RasterYSize
    # 读取指定波段
    band = dataset.GetRasterBand(1)
    # 该波段下的内容转二维矩阵
    im_datas = band.ReadAsArray(0, 0, im_width, im_height)
    # 像素坐标读数据
    data = im_datas[int(px), int(py)]
    res = {
        'val': str(data)
    }
    # 查看波段数
    # num_bands = dataset.RasterCount
    # print("波段数为", num_bands)
    # print('栅格矩阵的列数', im_width)
    # print('栅格矩阵的行数', im_height)
    # print('波段', band)
    # print('im_datas', im_datas)
    # print('该像素坐标下的val', data)
    # 释放内存
    del dataset
    return res
